const {
  baseDir,
  getModules,
} = require('./utils')
const utils = require('./utils')
const fs = require('fs')
const path = require('path')
const shell = require('shelljs')
const inquirer = require('inquirer')

// 是否复制到主入口
const isCopyToEntry = true
const isFolded = false

const ENTRY_DIR_NAME = 'qiankun-demo-main'
const ENTRY_PATH = path.join(baseDir, ENTRY_DIR_NAME)
const DIST_ALL = 'dist-all'
const DIST_ALL_PATH = path.join(ENTRY_PATH, DIST_ALL)


async function run() {
  const modules = getModules()
  const MODULE_ALL = 'all'
  const {name: project} = await inquirer.prompt([
    {
      type: 'list',
      name: 'name',
      message: '选择要打包的项目',
      choices: [MODULE_ALL, ...modules]
    }
  ])


  if (project === MODULE_ALL) {
    // 调整顺序，确保首先打包entry
    const entryIndex = modules.findIndex(item => item === ENTRY_DIR_NAME)
    if (entryIndex !== 0) {
      utils.arrayMove(modules, entryIndex, 0)
    }

    for (let i = 0; i < modules.length; i++) {
      const item = modules[i]
      utils.colorLog(`✨ ⚡⚡⚡  开始构建：${item}`, `${i + 1}/${modules.length}`, 'white')
      await buildProject(item)
    }
  } else {
    await buildProject(project)
  }
  console.log('All complete!')
}

async function buildProject(project) {
  const projectDir = baseDir + project
  const pkg = require(path.join(projectDir, 'package.json'))
  const version = pkg.version
  const isEntry = project === ENTRY_DIR_NAME
  const buildStr = 'build'

  utils.colorLog(projectDir, buildStr + ' ' + project + ' v' + version, 'green')
  utils.cd(projectDir)
  // 开始构建
  utils.exec(`yarn run ${buildStr}`)

  if (isCopyToEntry) {

    if (isEntry) {
      shell.rm('-r', DIST_ALL_PATH)
    }

    if (!fs.existsSync(DIST_ALL_PATH)) {
      fs.mkdirSync(DIST_ALL_PATH)
    }

    const FROM_PATH = path.join(projectDir, 'dist')
    const TO_PATH = path.join(ENTRY_PATH, DIST_ALL, pkg.name)

    if (!isEntry || isFolded) {
      // 复制子模块
      if (fs.existsSync(TO_PATH)) {
        console.log('删除：' + TO_PATH)
        shell.rm('-r', TO_PATH)
      }
      utils.colorLog(`${FROM_PATH} -> ${TO_PATH}`, '复制到主入口', 'magenta')
      shell.cp('-R', FROM_PATH, TO_PATH)
    } else {
      // 调整主入口文件夹
      shell.cp('-R', FROM_PATH + '/*', DIST_ALL_PATH)
    }
  }
}

run()
